import React, { Component,PureComponent } from "react";
import { actions } from "mirrorx";
import { FormControl, Select,Message,Radio } from 'tinper-bee'
import FormList from 'components/FormList';
import { getValidateFieldsTrim } from "utils";
import moment from "moment";
import DatePicker from "bee-datepicker";
import SelectMonth from 'components/SelectMonth';
import PopDialog from 'components/Pop';
import FormError from 'components/FormError';
import InputNumber from 'bee-input-number';
import { RefIuapDept } from 'components/RefViews'

import zhCN from "rc-calendar/lib/locale/zh_CN";
import './index.less'

const FormItem = FormList.Item;
const { Option } = Select;
const { YearPicker } = DatePicker;
const format = "YYYY-MM-DD HH:mm:ss";
const formatYYYY = "YYYY";
let titleArr = ["新增", "修改", "详情"];

class PopupModal extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            btnFlag: 0,
            cancelFlag: false
        }
    }

    /**
     * 关闭Modal
     */
    onCloseEdit = (values) => {
        //this.setState({rowData: {}, btnFlag: 0});
        this.props.onCloseEdit(values);
    }

    /**
     * 提交表单信息
     */
    onSubmitEdit = () => {
        let _this = this;
        let { btnFlag } = _this.state;
        let { currentIndex, list } = this.props;

        _this.props.form.validateFields((err, _values) => {
            let values = getValidateFieldsTrim(_values);
            //放开校验
            if (err) {

                Message.create({ content: '数据填写错误', color: 'danger' });
            }
            if (!err) {
                values = _this.onHandleSaveData(values); 
                values.btnFlag = btnFlag; // 弹框状态标识
                

                if (btnFlag == 1) {
                    list[currentIndex] = values;
                    list[currentIndex].persistStatus = "upd";
                } else {
                    values.persistStatus = "new";
                    list.push(values);
                }
                delete values.btnFlag;
                _this.onCloseEdit(list);
                //actions.monitorSample.updateState({ list });
            }
        });
    }

    /**
     *
     * @description 处理保存数据
     * @param {Object} values 待处理数据
     */
    onHandleSaveData = (values) => {
        let _this = this,
            {list,selectedIndex} = this.props,
            resObj = {};
        
        resObj = Object.assign({}, list[selectedIndex] || {}, values);
        
        //修改状态日期格式化
        if (resObj.dsenddate) {
            resObj.dsenddate = resObj.dsenddate.format(format);
        }
        _this.onHandleRef(resObj);  //暂时注释
        return resObj;
    }

    onHandleRef = (values) => {
        let arr = ['depositBankId', 'currencyId'];
        for (let i = 0, len = arr.length; i < len; i++) {
            let item = JSON.parse(values[arr[i]]);
            values[arr[i]] = item['refpk'] || "ceshi";
        }
    }

    /**
     *
     * @description 底部按钮是否显示处理函数
     * @param {Number} btnFlag 为页面标识
     * @returns footer中的底部按钮
     */
    onHandleBtns = (btnFlag) => {
        let _this = this;
        let btns = [

            {
                label: '取消',
                fun: this.onCloseEdit,
                shape: 'border'
            },
            {
                label: '确定',
                fun: _this.onSubmitEdit,
                colors: 'primary'
            },
        ];

        if (btnFlag == 2) {
            btns = [];
        }
        return btns;
    }

    renderFunc = () => {
        let {ColumnsData,list,currentIndex} = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let childRowData = list[currentIndex] || {};
        let dom = [];
        ColumnsData.forEach(item => {
            switch(item.type) {
                case 'FormControl':
                        dom.push(<FormItem
                                className="time"
                                label={item.zhname}
                            >
                                <FormControl disabled={item.edit}
                                    {...getFieldProps(`${item.enname}`,{
                                        initialValue: childRowData[item.enname],
                                    })}
                                />
                        </FormItem>);
                        break;
                case 'InputNumber':
                    dom.push(<FormItem
                                className="time"
                                label={item.zhname}
                            >
                                <InputNumber iconStyle="one" step={1} disabled={item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : -1,
                                        rules: [{required: true }],
                                    })}
                                />
                    </FormItem>);
                            break;
                case 'DatePicker':
                        dom.push(<FormItem
                                className="time"
                                label={item.zhname}
                            >
                                <DatePicker className='form-item' format={format} disabled={item.edit}
                                    {...getFieldProps('dsenddate', {
                                        initialValue: childRowData[item.enname] && moment(childRowData[item.enname]),
                                        validateTrigger: 'onBlur',
                                        rules: [{ required: false, message: '请选择领取时间', }],
                                    })}
                                />
                        </FormItem>);
                            break;
                case 'RefIuapDept':
                        dom.push(<FormItem
                                className="time"
                                label={item.zhname}
                            >
                                <RefIuapDept
                                    disabled={item.edit}
                                    placeholder="请选择物料"
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue: JSON.stringify({
                                            refname: childRowData[item.enname] || '自定义',
                                            refpk: childRowData[item.enname] || '1'
                                        }),
                                        rules: [{
                                            message: '请选择物料',
                                            pattern: /[^({"refname":"","refpk":""}|{"refpk":"","refname":""})]/
                                        }]
                                    })}
                                    backdrop={false}
                                />
                        </FormItem>);
                            break;
                case 'Select':
                        dom.push(<FormItem
                                className="time"
                                label={item.zhname}
                            >
                                <Select
                                    disabled={item.edit}
                                    {
                                    ...getFieldProps(`${item.enname}`, {
                                        initialValue: childRowData[item.enname] || '1',
                                    })
                                    }
                                >
                                    <Option value="1">自由</Option>
                                    <Option value="2">审批通过</Option>
                                </Select>
                                <FormError errorMsg={getFieldError(`${item.enname}`)} />
                        </FormItem>);
                            break;
                    case 'Bool':
                            dom.push(<FormItem
                                    className="time"
                                    label={item.zhname}
                                >
                                    <Radio.RadioGroup
                                    disabled={item.edit}
                                        {
                                        ...getFieldProps(`${item.enname}`, {
                                            initialValue: childRowData[item.enname] || '1',
                                        }
                                        ) }
                                    >
                                        <Radio value="2">是</Radio>
                                        <Radio value="1">否</Radio>
                                    </Radio.RadioGroup>
                                    <FormError errorMsg={getFieldError(`${item.enname}`)} />
                            </FormItem>);
                                break;
                    default: break;
            }
        })
        return dom;
    }


    render() {
        const _this = this;
        let { form, editModelVisible,ColumnsData } = _this.props;
        let { btnFlag } = _this.state;
        let { getFieldProps, getFieldError } = form;
        let btns = _this.onHandleBtns(btnFlag);


        return (

            <PopDialog
                show={editModelVisible}
                title={titleArr[btnFlag]}
                size='lg'
                btns={btns}
                autoFocus={false}
                enforceFocus={false}
                close={this.onCloseEdit}
                className="single-table-pop-model"
            >


                <FormList>
                     {_this.renderFunc()}
                </FormList>

            </PopDialog>
        )
    }
}

export default FormList.createForm()(PopupModal);
